import { random } from '/imports/lib/random';
import { selectData } from './createSelectData';
import SimpleSchema from '/imports/lib/SimpleSchema';

const result = {
  type: {},
  numberOfPeople: {},
  policy:{}
};

const findDisplayName = (id, source) => {
  for (let i = 0; i < source.length; i++) {
    if (source[i].id == id) {
      return source[i].text;
    }
  }
};

const setSelectVal = () => {
  let typeArr = $('#channel-info-type').val().split('_');
  result.type.name = typeArr[0] || 'group';
  result.type.displayName = typeArr[1] || 'group';
  result.numberOfPeople.name = $('#channel-info-number-of-user').val() || '51-200';
  result.numberOfPeople.displayName = findDisplayName($('#channel-info-number-of-user').val() || '51-200', selectData.numberOfPeople);
  result.policy.name = $('#channel-info-policy').val();
  result.policy.displayName = findDisplayName($('#channel-info-policy').val(), selectData.policy);
  result.policy.apply = $('#channel-info-apply-policy:checked').val() ? true : false;
};

const validationChannelName = new SimpleSchema({
  name: {
    type: String,
    min: 2,
    max: 40,
    label: '频道名称'
  }
});

const validationChannelId = new SimpleSchema({
  channelId: {
    type: String,
    min: 4,
    max: 16,
    regEx: /^[a-zA-Z0-9_]{4,16}$/,
    label: '频道ID'
  }
});

// const getDefaultTheme = () => {};

// 获取随机公共图片作为cover
const getDefaultCover = () => {
  const r = random(10);

  const arr = [
    'art', 'city', 'opera', 'prospect', 'rest', 'sport', 'study', 'travel', 'view', 'work'
  ];

  const filePath =  `/img/covers/${arr[r-1]}.jpg`;

  return filePath;
};

Template.create.onCreated(function () {
  this.isSettedInfo = new ReactiveVar(false);
  this.isSettedName = new ReactiveVar(false);
  this.isCreatingChannel = new ReactiveVar(false);
});

Template.create.helpers({
  isSettedInfo() {
    return Template.instance().isSettedInfo.get();
  },
  isSettedName() {
    return Template.instance().isSettedName.get();
  },
  isCreatingChannel() {
    return Template.instance().isCreatingChannel.get();
  }
});

Template.create.events({
  // step 1
  'click #submit-channel-info'(event, instance) {
    setSelectVal();
    instance.isSettedInfo.set(true);
  },
  // step 2
  'keypress #channel-name, click #submit-channel-name'(event, instance) {
    try {
      if (event.keyCode && event.keyCode !== 13) {
        return;
      }

      if ($('#channel-name-help').hasClass('text-danger')) {
        $('#channel-name-help')
          .removeClass('text-danger')
          .addClass('text-muted')
          .text('这将会作为新频道的名称，之后你可以随意修改它');
      }

      validationChannelName.validate({
        name: $('#channel-name').val()
      });

      result.name = $('#channel-name').val();
      instance.isSettedName.set(true);
    } catch (error) {
      if (error.details) {
        $('#channel-name-help')
          .removeClass('text-muted')
          .addClass('text-danger')
          .text(error.details[0].message);
      }
    }
  },
  'click #back-create-channel-info'(event, instance) {
    instance.isSettedInfo.set(false);
  },
  // step 3
  'keypress #channel-id, click #create-channel'(event, instance) {
    try {
      if (event.keyCode && event.keyCode !== 13) {
        return;
      }

      $('#channel-id-help').text('');

      validationChannelId.validate({
        channelId: $('#channel-id').val()
      });

      result.channelId = $('#channel-id').val();

      result.cover = getDefaultCover();

      // owner info
      let user = Meteor.user();
      result.owner = {
        id: user._id,
        username: user.username,
        avatar: user.profile.avatar
      };

      instance.isSettedInfo.set(true);
      Meteor.call('createChannel', result, (err, res) => {
        if (err) {
          $('#channel-id-help').text(err.reason);
        }
        if (res) {
          // 成功后直接跳转
          Router.go(`/channel/${result.channelId}`);
        }
        instance.isSettedInfo.set(false);
        instance.isSettedName.set(false);
      });
    } catch (error) {
      if (error.details && error.details[0].type === 'regEx') {
        $('#channel-id-help').text('频道ID格式错误，只能包含字母，数字和下划线');
      } else {
        $('#channel-id-help').text(error.details[0].message);
      }
    }
  },
  'click #back-create-channel-name'(event, instance) {
    instance.isSettedName.set(false);
  },
});

Template.createChannelName.helpers({
  type() {
    // console.log(result)
    if (result.type && result.type.displayName)
      return result.type.displayName;
  }
});

Template.createChannelId.helpers({
  name() {
    if (result.name)
      return `"${result.name}"`;
  }
});